from flask import Blueprint, request, render_template, session, g, make_response
import random, string
import uuid
import json

user_api = Blueprint('book', __name__, url_prefix='/book')

from toutiao.model.db_routing import User, Relation


@user_api.route('/book_list')
def book_list():
    return '课程列表'


@user_api.route('/code', methods=['GET'])
def get_code():
    code = ''.join(random.choices(string.digits, k=6))

    return code


# 登录
@user_api.route('/login', methods=['POST'])
def login():
    """登录"""

    phone = request.form.get('phone')
    code = request.form.get('code')

    user = User.query.filter(User.phone == phone).first()

    if not user:
        context = {'msg': '未找到该用户'}
        return context
    else:
        user_info = {
            'id': user.id,
            'account': user.account,
        }
        session['user'] = user.id

        cookie = str(uuid.uuid3(uuid.NAMESPACE_DNS, str(user.id)))

        token = make_response({'code': 200, 'msg': '登录成功'})
        token.set_cookie('token', cookie)
        return token


@user_api.route('/examine', methods=['GET', 'POST'])
def profile():
    """查看用户资料"""
    user_id = session.get('user')
    user = User.query.filter_by(id=user_id).first()
    if user:
        info = {
            'account': user.account,
            'password': user.password,
        }
        return {'msg': '查看用户信息', 'data': info}
    else:
        return {'msg': '没有此用户'}
        dingbiandeshusyouliangtouniugongniuduimuniushuolove

@user_api.route('/logout',methods=['GET'])
def logout():

    session.clear()
    return '退出登录'


